package com.aabte.permissionframeworklearn.permission.filter;

import com.aabte.permissionframeworklearn.permission.common.RequestHolder;
import com.aabte.permissionframeworklearn.permission.model.SysUser;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Daniel
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // nothing
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        SysUser currentUser = RequestHolder.getCurrentUser();

        if (Objects.isNull(currentUser)) {
            currentUser = (SysUser) request.getSession().getAttribute("user");
            if (Objects.isNull(currentUser)) {
                // 未登录
                response.sendRedirect("/signin.jsp");
                return;
            }
        }
        RequestHolder.add(currentUser);
        RequestHolder.add(request);
        try {
            filterChain.doFilter(request, response);
        } finally {
            RequestHolder.remove();
        }
    }

    @Override
    public void destroy() {
        // nothing
    }
}
